<template>
  <div class="user-list">
    <!-- 搜索表单 -->
    <a-card class="search-card">
      <a-form :model="searchForm" layout="horizontal">
        <a-row :gutter="16">
          <a-col :span="6">
            <a-form-item field="userAccount" label="用户账号">
              <a-input
                v-model="searchForm.userAccount"
                placeholder="请输入用户账号"
              />
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item field="userName" label="用户名称">
              <a-input
                v-model="searchForm.userName"
                placeholder="请输入用户名称"
              />
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item field="userRole" label="用户角色">
              <a-select
                v-model="searchForm.userRole"
                placeholder="请选择角色"
                allow-clear
              >
                <a-option value="user">普通用户</a-option>
                <a-option value="admin">管理员</a-option>
                <a-option value="ban">禁用用户</a-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item>
              <a-space>
                <a-button type="primary" @click="loadData">
                  <template #icon>
                    <icon-search />
                  </template>
                  查询
                </a-button>
                <a-button @click="resetSearch">
                  <template #icon>
                    <icon-refresh />
                  </template>
                  重置
                </a-button>
              </a-space>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-card>

    <!-- 操作按钮 -->
    <a-card class="action-card">
      <a-row>
        <a-col :span="24" style="text-align: left">
          <a-space>
            <a-button type="primary" @click="openAddModal">
              <template #icon>
                <icon-plus />
              </template>
              新增用户
            </a-button>
            <a-button
              type="primary"
              status="danger"
              @click="batchDelete"
              :disabled="selectedKeys.length === 0"
            >
              <template #icon>
                <icon-delete />
              </template>
              批量删除
            </a-button>
            <a-button @click="loadData">
              <template #icon>
                <icon-refresh />
              </template>
              刷新
            </a-button>
          </a-space>
        </a-col>
      </a-row>
    </a-card>

    <!-- 用户表格 -->
    <a-card class="table-card">
      <a-table
        :columns="columns"
        :data="userList"
        :pagination="pagination"
        :loading="loading"
        :row-selection="rowSelection"
        @page-change="onPageChange"
        @page-size-change="onPageSizeChange"
      >
        <!-- 用户角色 -->
        <template #userRole="{ record }">
          <a-tag v-if="record.userRole === 'admin'" color="blue">管理员</a-tag>
          <a-tag v-else-if="record.userRole === 'user'" color="green"
            >普通用户</a-tag
          >
          <a-tag v-else-if="record.userRole === 'ban'" color="red"
            >禁用用户</a-tag
          >
          <a-tag v-else color="gray">未知</a-tag>
        </template>

        <!-- 用户头像 -->
        <template #userAvatar="{ record }">
          <a-avatar :size="32" shape="circle">
            <img
              v-if="record.userAvatar"
              :src="record.userAvatar"
              alt="avatar"
            />
            <icon-user v-else />
          </a-avatar>
        </template>

        <!-- 状态 -->
        <template #isDelete="{ record }">
          <a-tag v-if="record.isDelete === 0" color="green">正常</a-tag>
          <a-tag v-else-if="record.isDelete === 1" color="red">已删除</a-tag>
        </template>

        <!-- 操作列 -->
        <template #operations="{ record }">
          <a-space>
            <a-button type="text" size="small" @click="openEditModal(record)"
              >编辑</a-button
            >
            <a-button
              type="text"
              size="small"
              status="danger"
              @click="confirmDelete(record)"
              >删除</a-button
            >
          </a-space>
        </template>
      </a-table>
    </a-card>

    <!-- 新增/编辑用户对话框 -->
    <a-modal
      v-model:visible="modalVisible"
      :title="modalType === 'add' ? '新增用户' : '编辑用户'"
      @cancel="closeModal"
      @before-ok="handleModalOk"
    >
      <a-form
        ref="userFormRef"
        :model="userForm"
        label-align="right"
        auto-label-width
      >
        <a-form-item
          field="userAccount"
          label="用户账号"
          :rules="[{ required: true, message: '用户账号不能为空' }]"
        >
          <a-input
            v-model="userForm.userAccount"
            placeholder="请输入用户账号"
          />
        </a-form-item>
        <a-form-item
          v-if="modalType === 'add'"
          field="userPassword"
          label="用户密码"
          :rules="[{ required: true, message: '用户密码不能为空' }]"
        >
          <a-input-password
            v-model="userForm.userPassword"
            placeholder="请输入用户密码"
          />
        </a-form-item>
        <a-form-item
          field="userName"
          label="用户名称"
          :rules="[{ required: true, message: '用户名称不能为空' }]"
        >
          <a-input v-model="userForm.userName" placeholder="请输入用户名称" />
        </a-form-item>
        <a-form-item
          field="userRole"
          label="用户角色"
          :rules="[{ required: true, message: '请选择用户角色' }]"
        >
          <a-select v-model="userForm.userRole" placeholder="请选择角色">
            <a-option value="user">普通用户</a-option>
            <a-option value="admin">管理员</a-option>
            <a-option value="ban">禁用用户</a-option>
          </a-select>
        </a-form-item>
        <a-form-item field="userAvatar" label="用户头像">
          <a-upload
            action="/api/file/upload"
            :file-list="fileList"
            list-type="picture-card"
            :limit="1"
            @success="handleUploadSuccess"
          >
            <template #upload-button>
              <div class="upload-button">
                <icon-plus />
                <div>上传头像</div>
              </div>
            </template>
          </a-upload>
        </a-form-item>
        <a-form-item field="userProfile" label="用户简介">
          <a-textarea
            v-model="userForm.userProfile"
            placeholder="请输入用户简介"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import {
  UserControllerService,
  UserQueryRequest,
  UserUpdateRequest,
  UserAddRequest,
} from "../../../../generated";
import { Message, Modal } from "@arco-design/web-vue";
import { useStore } from "vuex";

const store = useStore();

// 表格列定义
const columns = [
  { title: "ID", dataIndex: "id", width: 80 },
  { title: "用户账号", dataIndex: "userAccount" },
  { title: "用户名称", dataIndex: "userName" },
  {
    title: "用户头像",
    dataIndex: "userAvatar",
    slotName: "userAvatar",
    width: 80,
  },
  {
    title: "用户角色",
    dataIndex: "userRole",
    slotName: "userRole",
    width: 120,
  },
  { title: "创建时间", dataIndex: "createTime" },
  { title: "更新时间", dataIndex: "updateTime" },
  { title: "状态", dataIndex: "isDelete", slotName: "isDelete", width: 80 },
  {
    title: "操作",
    dataIndex: "operations",
    slotName: "operations",
    width: 150,
    fixed: "right",
  },
];

// 搜索表单数据
const searchForm = reactive({
  userAccount: "",
  userName: "",
  userRole: "",
  current: 1,
  pageSize: 10,
});

// 用户表单数据
const userForm = reactive<UserAddRequest & UserUpdateRequest & { id?: number }>(
  {
    userAccount: "",
    userPassword: "",
    userName: "",
    userRole: "user",
    userAvatar: "",
    userProfile: "",
  }
);

// 用户列表数据
const userList = ref<any[]>([]);
const total = ref(0);
const loading = ref(false);
const modalVisible = ref(false);
const modalType = ref<"add" | "edit">("add");
const userFormRef = ref(null);
const fileList = ref<any[]>([]);
const selectedKeys = ref<number[]>([]);

// 分页配置
const pagination = reactive({
  total: 0,
  current: 1,
  pageSize: 10,
  showTotal: true,
  showJumper: true,
  showPageSize: true,
});

// 表格选择配置
const rowSelection = {
  type: "checkbox",
  showCheckedAll: true,
  onlyCurrent: false,
  onChange: (selectedRowKeys: number[]) => {
    selectedKeys.value = selectedRowKeys;
  },
};

// 加载用户数据
const loadData = async () => {
  loading.value = true;
  try {
    const req = {
      ...searchForm,
      current: pagination.current,
      pageSize: pagination.pageSize,
    };
    const res = await UserControllerService.listUserByPageUsingPost(req);

    if (res.code === 0 && res.data) {
      userList.value = res.data.records || [];
      total.value = res.data.total || 0;
      pagination.total = total.value;
    } else {
      Message.error("获取用户列表失败：" + (res.message || "系统错误"));
    }
  } catch (error) {
    Message.error("获取用户列表失败：" + error);
  } finally {
    loading.value = false;
  }
};

// 重置搜索条件
const resetSearch = () => {
  searchForm.userAccount = "";
  searchForm.userName = "";
  searchForm.userRole = "";
  pagination.current = 1;
  loadData();
};

// 分页变化
const onPageChange = (current: number) => {
  pagination.current = current;
  loadData();
};

// 每页条数变化
const onPageSizeChange = (pageSize: number) => {
  pagination.pageSize = pageSize;
  pagination.current = 1;
  loadData();
};

// 打开新增用户对话框
const openAddModal = () => {
  modalType.value = "add";
  resetUserForm();
  modalVisible.value = true;
};

// 打开编辑用户对话框
const openEditModal = (record: any) => {
  modalType.value = "edit";
  resetUserForm();

  // 填充表单
  userForm.id = record.id;
  userForm.userAccount = record.userAccount;
  userForm.userName = record.userName;
  userForm.userRole = record.userRole;
  userForm.userAvatar = record.userAvatar;
  userForm.userProfile = record.userProfile;

  // 如果有头像，显示头像
  if (record.userAvatar) {
    fileList.value = [
      {
        url: record.userAvatar,
        name: "avatar.png",
        status: "done",
      },
    ];
  }

  modalVisible.value = true;
};

// 重置用户表单
const resetUserForm = () => {
  userForm.id = undefined;
  userForm.userAccount = "";
  userForm.userPassword = "";
  userForm.userName = "";
  userForm.userRole = "user";
  userForm.userAvatar = "";
  userForm.userProfile = "";
  fileList.value = [];
};

// 关闭对话框
const closeModal = () => {
  modalVisible.value = false;
};

// 上传头像成功回调
const handleUploadSuccess = (file: any, fileList: any[]) => {
  if (file.response && file.response.code === 0) {
    userForm.userAvatar = file.response.data;
    Message.success("上传成功");
  } else {
    Message.error("上传失败: " + (file.response?.message || "未知错误"));
  }
};

// 提交用户表单
const handleModalOk = async () => {
  try {
    if (modalType.value === "add") {
      const res = await UserControllerService.addUserUsingPost(userForm);
      if (res.code === 0) {
        Message.success("新增用户成功");
        loadData();
      } else {
        Message.error("新增用户失败: " + (res.message || "系统错误"));
        return false;
      }
    } else {
      // 编辑用户
      const res = await UserControllerService.updateUserUsingPost(userForm);
      if (res.code === 0) {
        Message.success("更新用户成功");
        loadData();
      } else {
        Message.error("更新用户失败: " + (res.message || "系统错误"));
        return false;
      }
    }
  } catch (error) {
    Message.error("操作失败: " + error);
    return false;
  }
};

// 确认删除用户
const confirmDelete = (record: any) => {
  Modal.warning({
    title: "确认删除",
    content: `确定要删除用户 ${record.userName} (${record.userAccount}) 吗？`,
    okButtonProps: { status: "danger" },
    onOk: () => deleteUser(record.id),
  });
};

// 删除用户
const deleteUser = async (id: number) => {
  try {
    const res = await UserControllerService.deleteUserUsingPost({ id });
    if (res.code === 0) {
      Message.success("删除成功");
      loadData();
    } else {
      Message.error("删除失败: " + (res.message || "系统错误"));
    }
  } catch (error) {
    Message.error("删除失败: " + error);
  }
};

// 批量删除
const batchDelete = () => {
  if (selectedKeys.value.length === 0) {
    Message.warning("请选择要删除的用户");
    return;
  }

  Modal.warning({
    title: "批量删除",
    content: `确定要删除选中的 ${selectedKeys.value.length} 个用户吗？`,
    okButtonProps: { status: "danger" },
    onOk: async () => {
      try {
        // 实际开发中应该有批量删除接口
        let failCount = 0;
        for (const id of selectedKeys.value) {
          const res = await UserControllerService.deleteUserUsingPost({ id });
          if (res.code !== 0) {
            failCount++;
          }
        }

        if (failCount === 0) {
          Message.success("批量删除成功");
        } else {
          Message.warning(
            `部分用户删除失败，成功删除 ${
              selectedKeys.value.length - failCount
            } 个，失败 ${failCount} 个`
          );
        }

        selectedKeys.value = [];
        loadData();
      } catch (error) {
        Message.error("批量删除失败: " + error);
      }
    },
  });
};

// 组件挂载后加载数据
onMounted(() => {
  loadData();
});
</script>

<style scoped>
.user-list {
  padding: 0;
}

.search-card,
.action-card,
.table-card {
  margin-bottom: 16px;
}

.upload-button {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
</style>
